<template>
  <div id="courseCfg">
    <h4>课程配置</h4>
    <el-form size="default" :inline="true">
      <el-form-item label="选择团队组">
        <el-select v-model="teamusergroupid" clearable placeholder="请选择" style="width: 220px">
          <el-option v-for="item in selectGroup" :key="item.name" :label="item.name" :value="item.ID">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="start" type="primary" size="default">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item>
        <el-button :disabled="disabled" @click="setCourse" type="primary" size="default">设置课程</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table height="71vh" style="width: 100%" :data="tableData" @selection-change="handleSelectionChange"
        v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="团队成员" :formatter="({ user }) => user.name" width="200"></el-table-column>
        <el-table-column prop="teamusergroupid" label="分组"
          :formatter="({ teamusergroupid }) => formatGroupName(teamusergroupid)" width="200"></el-table-column>
        <el-table-column prop="course" label="课程包">
          <template #default="{ row }">
            <div class="catebag-box" v-if="row.userCourseCatebags">
              <el-tag class="catebag-intable-label" text type="primary" effect="plain" size="default"
                v-for="(v, k) in row.userCourseCatebags" v-text="v" :key="k">
              </el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pager" size="default" :page-size="limit" :page-sizes="pageSizes" :total="totalCount"
        layout="total, sizes, prev, pager, next" @current-change="changePage" @size-change="handleSizeChange"
        :current-page="Math.floor(offset / limit) + 1">
      </el-pagination>
    </div>
    <!-- 弹窗 课程包配置 -->
    <el-dialog class="catebag-cfg-container" title="课程配置" v-model="courseCfgDialogVisible" min-width='80vw' width='80vw'
      :before-close="close" top="0">
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          课程配置
        </span>
      </template>
      <div class="container-box">
        <el-form label-position="top" label-width="210px" size="default">
          <el-form-item label="成员">
            <el-scrollbar>
              <div class="container-header">
                <el-text siez="default" type="primary" v-for="(v, k) in multipleSelection" :key="k">
                  {{ v.user?.name }}{{ k == multipleSelection.length - 1 ? "" : "、" }}
                </el-text>
              </div>
            </el-scrollbar>
          </el-form-item>
        </el-form>
        <div class="container-content">
          <div>
            <el-form label-position="top" label-width="210px" size="default">
              <el-form-item label="配置团队成员可见课程:">
                <el-scrollbar>
                  <el-checkbox-group class="catebag-list" v-model="checkedCatebags" size="default">
                    <div class="form-item" v-for="(v, k) in groupedByCatebagArr" :key="k"
                      @mouseenter="showCourseList(v)">
                      <el-checkbox class="form-item-check-box" :value="v.cID">{{ v.name }}</el-checkbox>
                      <div class="desc cursor-pointer">
                        <span>{{ v.info }}</span>
                      </div>
                      <!-- <div class="btn-box">
                        <el-button type='primary' link @click="showCourse(v.ID)">查看课程</el-button>
                      </div> -->
                    </div>
                  </el-checkbox-group>
                </el-scrollbar>
              </el-form-item>
              <el-form-item>
              </el-form-item>
            </el-form>
            <el-button class="save-btn" type="primary" size="default"
              @click="submitUpdateUserCourseGroup">保存</el-button>
          </div>
          <div class="container-right">
            <el-table class="container-right-table" width="100%" stripe :data="courseList">
              <template v-slot:empty>
                <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
              </template>
              <!-- <el-table-column type="index" width="50" /> -->
              <el-table-column prop="name" label="课程名" width="">
                <template #header>
                  {{ selectedCateBagName }}({{ courseList.length }})
                </template>
                <template #default="{ row }">
                  {{ row.name }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useStore } from "vuex";
import {
  asyncSelectPackageCatebagRelation,
  asyncaddUsercourse,
  asyncfindteamusergroup,
  asyncselectUsercourse,
  asyncselectteamcoursegroup,
  asyncselectteamuser
} from "../../../api";
import { Storekey } from "../../../interface";
import Alymodel from "../../../mysql_interface/model";
import { default as Studycodemodel } from "../../../mysql_interface/studycodemodel";
import { getGroupedByCatebagArr } from "../../../util/cloudClass";
import { courseCatebag } from "../data/data";

const defaultPIDs = courseCatebag.map(e => (e.pID))

const store = useStore(Storekey)
// 当前登录用户
const user = computed(() => {
  return store.state.user;
});
const teamId = computed(() => {
  return Number(user.value?.teamid);
});

onMounted(async () => {
  await start()
})
// 课程包
const checkedCatebags = ref<any[]>([])
async function start() {
  loading.value = true
  await getTeamGroupInfo()
  // 成员-课程
  await getUsercourse()
  // 获取团队代理商课包
  const { rows, count } = await asyncselectteamcoursegroup({ teamid: teamId.value })
  // 没有查到就用前端默认的7个代理商课包
  const pIds = rows?.length ? rows.map(e => Number(e.coursegroupid)) : defaultPIDs
  // 代理商课包-课程组
  await getPackageCatebagRelation(pIds)
  tableData.value = tableData.value.map(e => {
    return { ...e, userCourseCatebags: formatUserCourseCatebag(e) }
  });
  loading.value = false;
}

const loading = ref(false)
const tableData = ref<Studycodemodel.Iteamuser[]>([]);
const totalCount = ref(0);
const limit = ref(20)
const offset = ref(0)
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500]
// const teamInfo = ref<Studycodemodel.Iteam>({})
const group = ref<Studycodemodel.Iteamusergroup[]>([])
const teamusergroupid = ref()
const selectGroup = computed(() => {
  return [{ ID: '全部', name: '全部' }, { ID: '未分组', name: '未分组' }, ...group.value]
})
async function getTeamGroupInfo() {
  // 获取团队信息
  // teamInfo.value = await asyncgetteam({ ID: teamId.value });
  // 获取团队分组
  group.value = await asyncfindteamusergroup({ teamid: teamId.value });
  let groupId = teamusergroupid.value === '未分组' ? null : teamusergroupid.value
  // 获取团队成员
  let cond = { teamid: teamId.value, _limit: limit.value, _offset: offset.value, }
  if (groupId !== '全部') { cond.teamusergroupid = groupId }
  const { rows, count } = await asyncselectteamuser(cond);
  tableData.value = rows
  totalCount.value = count;
}

// 根据课程获取课程包
function formatUserCourseCatebag(row: Studycodemodel.Iteamuser) {
  let intableCateBagName: string[] = []
  let userId = row.userid
  matchCourseCateBag(userId, (catebag: Alymodel.IMcatebag) => {
    intableCateBagName.push(catebag.name || "")
  })
  return intableCateBagName
}
// 弹窗复选框成员课程包回填
function formatterCourseGroupCheckbox() {
  if (multipleSelection.value?.length === 1) {
    const selectedUid = multipleSelection.value[0].userid
    matchCourseCateBag(selectedUid, (catebag: Alymodel.IMcatebag) => {
      checkedCatebags.value.push(catebag.ID)
    })
  }
}
// 利用课程和课包-课程得出课程组名字
function matchCourseCateBag(uid: number, fn: (catebag: Alymodel.IMcatebag) => void) {

  let userCourse = userCourseMap.value[uid] || []
  let catebagMap = new Map<number, Alymodel.IMcatebag>();
  // 所有userCourseID
  const userCourseSet = new Set(userCourse.map(uc => uc.course_ID));

  for (const catebag of groupedByCatebagArr.value) {
    const packages = catebag.packages || [];
    for (const pkg of packages) {
      if (userCourseSet.has(pkg.course_ID)) {
        if (!catebagMap.has(catebag.cID)) {
          catebagMap.set(catebag.cID, catebag);
          fn(catebag);
        }
        break;
      }
    }
  }
}

// 获取团队成员课程配置 user_ID - course[]
const userCourseMap = ref<{ [uid: number]: Alymodel.IMusercourse[] }>({})
async function getUsercourse() {
  userCourseMap.value = await asyncselectUsercourse({
    teamid: teamId.value,
    user_ID: tableData.value.map(e => e.userid),
    _order: 'createtime'
  })
}
// 代理商课包-课程组关系
const groupedByCatebagArr = ref<Alymodel.GroupedByCatebag[]>([])
// 获取指定代理商课包 =》 课程 =》 课程组 关系 
const teamPackageCatebagRelation = ref<Alymodel.PackageCatebagRelation[]>([])
async function getPackageCatebagRelation(pID: number[]) {
  const { rows: data, count } = await asyncSelectPackageCatebagRelation({ ID: pID, })
  teamPackageCatebagRelation.value = data
  // 按课程包分组
  groupedByCatebagArr.value = getGroupedByCatebagArr(data)
}

const courseCfgDialogVisible = ref(false)
// 设置课程
function setCourse() {
  courseCfgDialogVisible.value = true
  showCourseList(groupedByCatebagArr.value[0])
  // 成员课程包回填
  formatterCourseGroupCheckbox()
}
const disabled = computed(() => {
  return !multipleSelection.value.length
})

// 多选框
const multipleSelection = ref<Studycodemodel.Iteamuser[]>([])
function handleSelectionChange(v: Studycodemodel.Iteamuser[]) {
  multipleSelection.value = v
}
// 保存
async function submitUpdateUserCourseGroup() {
  let uids = multipleSelection.value.map(e => (e.userid))
  // 删除
  let del_course_ID: number[] = []
  // 新增
  let add_course_ID: number[] = []

  groupedByCatebagArr.value.forEach(catebag => {
    catebag.packages?.forEach(pkgItem => {
      // 删除所有课程
      del_course_ID.push(pkgItem.course_ID as number)
      // 匹配复选框（CID）选中课程包，所有课程
      if (checkedCatebags.value.includes(catebag.cID)) {
        add_course_ID.push(pkgItem.course_ID as number)
      }
    })
  })
  let usercourse: { user_ID: number, course_ID: number, permission: number, }[] = []
  uids.forEach(uid => {
    add_course_ID.forEach(cid => {
      usercourse.push({
        user_ID: uid as number,
        course_ID: cid,
        permission: 100
      })
    })
  })
  try {
    await asyncaddUsercourse({
      teamid: teamId.value,
      user_ID: uids,
      course_ID: del_course_ID,
      usercourse,
    })
    ElMessage.success("操作成功");
    close()
    start()
  } catch (e: any) {
    ElMessage.error(e);
  }
}

// hover单个课程组-课程
const selectedCateBagID = ref()
const courseList = ref<Alymodel.IMcourse[]>([])
const selectedCateBagName = ref("")
function showCourseList(v: Alymodel.GroupedByCatebag) {
  selectedCateBagID.value = v.cID
  selectedCateBagName.value = v.name || ""
  courseList.value = v.packages.sort((a, b) => (a.course_ID || 0) - (b.course_ID || 0));
}
// watch(selectedCateBagID, async () => {
//   const data = teamPackageCatebagRelation.value.find(e => e.ID === selectedCateBagID.value)
//   if (data) {
//     const cids = data.packege?.map(e => e.course_ID)
//     const { rows, count } = await asyncselectcourse({
//       teamid: teamId.value, ID: cids,
//       _limit: 1000,
//       _order: "ID",
//       _sortable: "ASC"
//     })
//     courseList.value = rows
//   }
// })

function changePage(val: number) {
  offset.value = limit.value * (val - 1);
  start()
}
const handleSizeChange = (val: number) => {
  limit.value = val
  start()
}
function close() {
  courseCfgDialogVisible.value = false
  checkedCatebags.value = []
}

// formatter
function formatGroupName(teamusergroupid: number) {
  const d = group.value?.find((v: study.Iteamusergroup) => v.ID == teamusergroupid);
  return d ? d.name : '未分组';
}
</script>

<style scoped>
.container-box {
  padding: 0 20px;
}

.container-header {
  max-height: 100px;
}

.container-content {
  display: flex;
}

.form-item {
  padding: 30px 20px;
  display: flex;
  align-items: flex-start;
}

.form-item:hover {
  background: rgb(250, 250, 250);
  border-radius: 4px;
}

.form-item-check-box {
  flex: 0 0 auto;
  display: inline-block;
  width: 180px;
  line-height: 30px;
  font-size: 14px !important;
  font-weight: bold;
}

.desc {
  text-indent: 2rem;
  padding: 0 20px;
  line-height: 30px;
  font-size: 14px;
  color: #7f7f7f;
  /* max-height: 200px; */
  /* 隐藏超出容器的部分 */
  overflow: hidden;
  /* 必须结合webkit-box */
  display: -webkit-box;
  /* 设置flex方向为纵向 */
  -webkit-box-orient: vertical;
  /* 显示的行数 */
  -webkit-line-clamp: 2;
  /* 允许文本换行 */
  white-space: normal;
  /* 使用省略号表示超出的文本 */
  text-overflow: ellipsis;
}

.desc:hover {
  background: rgb(250, 250, 250);
  border-radius: 4px;
}

.save-btn {
  margin: 0 20px;
}

.btn-box {
  line-height: 30px;
}

.container-right {
  min-width: 300px;
}

.catebag-list,
.container-right {
  height: calc(100vh - 300px);
}

.container-right-table {
  height: calc(100vh - 220px);
  transition: background-color 0.3s ease;
}

.catebag-box {
  display: flex;
  flex-wrap: wrap;
}

.catebag-intable-label {
  margin: 4px;
  padding: 0 10px;
  box-sizing: border-box;
  border-radius: 3px;
  height: 30px;
}

.pager {
  margin-top: 10px;
  margin-right: 0;
  float: right;
}
</style>

<style>
#courseCfg .catebag-cfg-container {
  height: auto;
  /* overflow: hidden; */
}
</style>